/**
 * Created by admin on 16/2/21.
 */
//测试百度防御机制
"use strict";

var request = require('request');
var option = require('../unit/req_options.js');

const delay = 30;
let count = 1;
let resCount = 0;
let max = 9999;
let timer = null;
let shut = false;

var dic = 'qwertyuiopasdfghjklzxcvbnm1234567890';

let creat = num=> {
    let l = dic.length;
    let str = '';
    do {
        str += dic[num % l];
        num = Math.floor(num / l);
    } while (num > 0);
    return str;
};

class Test {
    constructor(index, cb) {
        this.index = index;
        let keyword = creat(index);
        this.url = `http://www.baidu.com/s?wd=${keyword}&ie=utf-8&pn=0`;
        request(
            option.set(encodeURI(this.url)),
            (err, res, html)=> {
                if (html === null) {
                    if(!shut)console.log(`Error:${this.index}`);
                    shutdown();
                } else {
                    cb(this);
                }
            }
        )
    }
}

let setOneProcess = ()=> {
    if (count >= max)return shutdown();
    let test = new Test(count, (t)=> {
        if(!shut)console.log(`Success:${t} - ${t.url}`);
        resCount++;
    });
    count++;
};

let shutdown = ()=> {
    shut=true;
    clearInterval(timer);
    timer = null;
    count = 1;
    resCount = 1;
};

module.exports = {
    start(){
        shut=false;
        if (timer == null) {
            timer = setInterval(setOneProcess, delay);
        } else {
            //noop
        }

    }
};

